﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using personalplaner.business;
using personalplaner.business.dienstplan;
using personalplaner.business.dienstplan.plancollection;
using personalplaner.business.enums;
using personalplaner.business.extensions;
using personalplaner.business.stamm;
using personalplaner.common.mvvm;
using personalplaner.common.mvvm.commands;
using personalplaner.servicemodel.dataaccess;

namespace personalplaner.plugins.plananalysis.viewmodels
{
	public class HolidayOverviewViewModel : BaseViewModel
	{
		public HolidayOverviewViewModel(DependencyObject parent)
            : base(parent)
        {
        }

		#region Commands

		ICommand _printcommand;
		public ICommand PrintCommand
		{
			get
			{
				if (_printcommand == null)
					_printcommand = new RelayCommand(OnPrintCommand, parameter => IsYearPlaned);
				return _printcommand;
			}
		}

		private void OnPrintCommand(object parameter)
		{
			var parent = Parent as HolidayOverview;
			if(parent==null)
				return;

			var el = parent.Grids.RenderNewElement();
			((FrameworkElement)el).HorizontalAlignment = HorizontalAlignment.Left;
			((FrameworkElement)el).VerticalAlignment = VerticalAlignment.Top;
			((FrameworkElement)el).Margin = new Thickness(40, 60, 40, 60);

			var pc = new PrintView();
			pc.Pages = new List<UIElement> { el };

			var mw = GetService<IMainWindowDisplayContainer>();
			mw.IsWaitVisible = true;
			
			var service = GetService<IMainWindowDisplayContainer>();
			service.AddSimpleContentItem(enDisplayItemType.Custom, pc, true);

		}

		#endregion

		#region Properties

		IList<PlanYear> _years;
		public IList<PlanYear> Years
		{
			get
			{
				if (_years == null)
				{
					var da = GetService<ICommonDataAccess>();
					var lst = da.GetActiveYears();
					_years = lst != null ? new ObservableCollection<PlanYear>(lst) : new ObservableCollection<PlanYear>();

					SelectedYear = (from a in _years where a.Status == business.enums.enStatus.Active select a).FirstOrDefault();
				}
				return _years;
			}
		}

		PlanYear _selectedYear;
		public PlanYear SelectedYear
		{
			get
			{
				return _selectedYear;
			}
			set
			{
				_selectedYear = value;
				RaisePropertyChanged("SelectedYear");

				SetData();
			}
		}

		int _prsId;
		public int PrsId
		{
			get { return _prsId; }
			set
			{
				_prsId = value;
				RaisePropertyChanged("PrsId");

				SetData();
			}
		}

		ObservableCollection<IDienstPlanRow> _collection;
		public ObservableCollection<IDienstPlanRow> Collection
		{
			get
			{
				if (_collection == null)
					_collection = new ObservableCollection<IDienstPlanRow>();
				return _collection;
			}
		}

		public bool IsYearPlaned
		{
			get
			{
				return Collection.Count > 0;
			}
		}

		IList<Feiertag> _feiertage;
		public IList<Feiertag> Feiertage
		{
			get
			{
				if (_feiertage == null)
				{
					if (SelectedYear == null)
						return null;

					var da = GetService<ICommonDataAccess>();
					var lst = da.GetFeiertage(SelectedYear.JahrId);
					_feiertage = lst != null ? new List<Feiertag>(lst) : new List<Feiertag>();
				}
				return _feiertage;
			}
		}

		static Color? HolidayColor { get; set; }

		static Color? SaturdayColor { get; set; }

		static Color? SundayColor { get; set; }

		#endregion

		#region implementation

		private void SetData()
		{
			if (PrsId <= 0 || SelectedYear == null)
				return;

			var da = GetService<IPlanDataAccess>();
			var cda = GetService<ICommonDataAccess>();
			var pda = GetService<IPersonDataAccess>();
			var options = GetService<IOptionsDataAccess>();
			bool colorweekend = options.ColorWeekendInPlan;

			HolidayColor = options.HolidayColor;
			SaturdayColor = options.SaturdayColor;
			SundayColor = options.SundayColor;


			var headers = cda.GetPlanedMonths(SelectedYear.JahrId);

			Collection.Clear();

			if (headers == null)
			{
				RaisePropertyChanged("Collection");
				RaisePropertyChanged("IsYearPlaned");
				return;
			}

			foreach (var header in headers)
			{
				var row = new SimpleRow
				{
					ID = header.ID,
					Name = header.Name
				};

				IList<PlanItem> lst = null;
				var tmp = da.GetPlanHolidays(PrsId, header.AtId, SelectedYear.JahrId);

				if (tmp != null)
					lst = (from a in tmp select new PlanItem { Datum = a.Date, DienstId = a.DienstId, Name = a.Name }).ToList();

				row.Initialize(header.Von, lst);


				//// set the background for all dienste that are holidays
				//if (lst != null)
				//{
				//    foreach (var itm in lst)
				//    {
				//        if (itm.Color == null || itm.Color == Colors.Transparent)
				//            itm.Color = HolidayColor;
				//    }
				//}

				// set the background for all holidays that are planed but not set yet
				var holidays = pda.GetHolidays(PrsId, header.Von.Year, header.Von.Month);
				if (holidays != null)
				{
					foreach (var holiday in holidays)
					{
						int begin = holiday.Von.Day;
						if (holiday.Von.Month != header.Von.Month)
							begin = 1;
						int end = holiday.Bis.Day;
						if (holiday.Bis.Month != header.Von.Month)
							end = DateTime.DaysInMonth(header.Von.Year, header.Von.Month);

						while (begin <= end)
						{
							var pi = (from planitm in row
							          where planitm.Datum.Day == begin
							          select planitm).FirstOrDefault();
							begin++;
							if (pi == null)
								continue;

							if (pi.Color == null || pi.Color == Colors.Transparent)
								pi.Color = HolidayColor;
							//pi.BackgroundColor = HolidayColor;
						}
					}
				}




				if (colorweekend)
					SetWeekendColor(row);

				Collection.Add(row);
			}

            RaisePropertyChanged("Collection");
			RaisePropertyChanged("IsYearPlaned");
		}

		private void SetWeekendColor(IEnumerable<PlanItem> items)
		{
			foreach (var item in items)
			{
				//if (item.Color != Colors.Transparent && item.Color != Colors.White)
				if (item.Color != null && !((Color) item.Color).IsEmptyColor())
					continue;

				if (item.Datum.DayOfWeek == DayOfWeek.Saturday)
				{
					item.Color = SaturdayColor;
				}
				else if (item.Datum.DayOfWeek == DayOfWeek.Sunday)
				{
					item.Color = SundayColor;
				}

				if (IsDayFeiertag(item.Datum))
				{
					item.Color = SundayColor;
				}
			}
		}

		private bool IsDayFeiertag(DateTime dateTime)
		{
			if (Feiertage == null)
				return false;

			var itms = from a in Feiertage where a.Von == dateTime select a;

			return itms.Count() > 0;
		}

		#endregion
	}
}
